<?php

namespace App\Models;

use DB;

class Order extends BaseModel
{
    protected $table = "order";

    public $back_category_id = 6;

    protected $rules = [
        'admin_id' => 'required',
        'shop_id' => 'required',
        'order_sn' => 'required',
        'buyer_id' => 'required',
        'buyer_name' => 'required|between:1,20',
        'buyer_address' => 'required',
        'mobile' => 'required|regex:/^1[3456789]{1}\d{9}$/',
//        'mobile' => ['required', 'regex:/^(1(([35][0-9])|(47)|[8][01236789]))\d{8}$/'],
//        'order_amount' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
    ];

    protected $message = [
        'admin_id.required' => '商户信息失败',
        'shop_id.required' => '店铺信息获取失败',
        'order_sn.required' => '订单编号获取失败',
        'buyer_id.required' => '用户信息获取失败',
        'buyer_name.required' => '请添加收货地址',
        'buyer_name.between' => '收货人姓名不能超过20个字',
        'buyer_address.required' => '请添加收货地址',
        'mobile.required' => '请添加收货地址',
        'mobile.regex' => '手机号格式不正确',
//        'order_amount.required' => '商品价格必须填写',
//        'order_amount.numeric' => '商品价格必须是纯数字',
//        'order_amount.regex' => '商品价格不能小于0',
    ];

    public $listType = [
        0 => '全部',
        1 => '超时',
        2 => '待付款',
        3 => '待配送',
        4 => '配送中',
        5 => '已完成',
    ];

    public function memberWaterBill()
    {
        return $this->hasOne('App\Models\MemberWaterBill', 'bill_id', 'id');
    }

    public function billOrder()
    {
        return $this->hasMany('App\Models\WaterBillOrder', 'mid', 'buyer_id');
    }

    public function payBillOrder()
    {
        return $this->hasOne('App\Models\WaterBillOrder', 'order_id', 'id');
    }

    public function bucket()
    {
        return $this->hasMany('App\Models\BucketLog', 'order_id', 'id');
    }

    public function memberBill()
    {
        return $this->hasOne('App\Models\MemberWaterBill', 'mid', 'buyer_id');
    }

    public function member()
    {
        return $this->hasOne('App\Models\Member', 'id', 'buyer_id');
    }

    public function orderGoods()
    {
        return $this->hasMany('App\Models\OrderGoods', 'order_id', 'id');
    }

    public function worker()
    {
        return $this->belongsTo('App\Models\Worker', 'worker_id', 'id');
    }

    public function getDetail()
    {
        $res = $this->_getJionOne('orderGoods', ['id' => request('id'), 'buyer_id' => $GLOBALS['mid']]);
        if (!$res) {
            $this->error = '该订单不存在';
            return false;
        }
        $picture = new Picture();
        $res = $res->toArray();
        foreach ($res['order_goods'] as &$v) {
            $v['goods_img'] = url('/') . $picture->config['savePath'] . $GLOBALS['admin_id'] . '/' . $v['goods_id'] . '_1.' . $picture->config['saveExt'];
        }
        $data[] = $res;
        $txtStr['status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['type'] = [0 => '在线支付', 1 => '线下支付'];
        $txtStr['dispatch'] = [1 => '正在派送', 2 => '已完成', 0 => '未派送', -1 => '过期超时'];
        $data = int_to_string($data, $txtStr);
        return $data[0];
    }

    public function getOrderList()
    {
        $keyword = request('keyword');
        if ($keyword) {
            $where['order_sn'] = ['like', '%' . $keyword . '%'];
        }
        $rows = $this->_getPageList($where);
        $txtStr['status'] = [0 => '已取消', 10 => '未付款', 20 => '已付款'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnOrderList($shopId)
    {
        $keyword = request('keyword');
        $buyer_name = request('buyer_name');
        $start = request('time-start');
        $end = request('time-end');
        if (!is_administrator()) {
            $where['admin_id'] = plat_admin_id();
        } else {
            $where = [];
        }
        if ($shopId) {
            $where['shop_id'] = $shopId;
        }
        $type = request('type', 0);
        //type  1:超时  2.待付款 3.待配送 4.配送中 5.已完成
        switch ($type) {
            case 1 :
                $where['dispatch'] = -1;
                break;
            case 2 :
                $where['status'] = 10;
                $where['type'] = 1;
                break;
            case 3 :
                $where['status'] = 20;
                $where['dispatch'] = 0;
                $orWhere = $where;
                $orWhere['status'] = 10;
                $orWhere['type'] = 1;
                $where['or'] = ['or', $orWhere];
                break;
            case 4 :
                $where['dispatch'] = 1;
                break;
            case 5 :
                $where['status'] = 20;
                $where['dispatch'] = 2;
                break;
            case 6 :
                $where['dispatch'] = -1;
                break;
            default:
        }
        $keyword && $where['order_sn'] = ['like', '%' . $keyword . '%'];
        $buyer_name && $where['buyer_name'] = ['like', '%' . $buyer_name . '%'];
        if ($start && !$end) {
            $timeArea = [strtotime($start), strtotime($start) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($end && !$start) {
            $timeArea = [strtotime($end), strtotime($end) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $timeArea[1] += 86399;
            $where['addtime'] = ['between', $timeArea];
        }
        $orderFields = 'id,shop_id,order_sn,created_at,order_amount,buyer_id,buyer_name,status,bill_id,buyer_address,mobile,bucket_num,back_bucket_num,type,dispatch,worker_id';
        $orderGoodsFields = 'admin_id,order_id,goods_id,goods_name,goods_num,goods_price,goods_category_id';
        $workerFields = 'id,name';
//        if (in_array($type,[4,5])) {
        $rows = $this->_getJoinTwoPageList('orderGoods', 'worker', $where, $orderFields, ['id' => 'desc'], 10, 10, $orderGoodsFields, [], $workerFields);
//        } else {
//            $rows = $this->_getJoinPageList('orderGoods', $where, $orderFields, ['id' => 'desc'], 10, 5, $orderGoodsFields);
//        }
        if ($rows['data']) {
            foreach ($rows['data'] as &$v) {
                $v['data_type'] = $type;
            }
        }
        $txtStr['status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['dispatch'] = [1 => '配送中', 2 => '已完成', 0 => '待接单', -1 => '已超时'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getMemberOrderList()
    {
        $keyword = request('keyword');
        $start = request('time-start');
        $end = request('time-end');
        $where['shop_id'] = $GLOBALS['shop_id'];
        $where['buyer_id'] = $GLOBALS['mid'];
        if (!($where['shop_id'] && $where['buyer_id'])) {
            $this->error = '非法操作';
            return false;
        }
        $keyword && $where['order_sn'] = $keyword;
        if ($start && !$end) {
            $timeArea = [strtotime($start), strtotime($start) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($end && !$start) {
            $timeArea = [strtotime($end), strtotime($end) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $timeArea[1] += 86399;
            $where['addtime'] = ['between', $timeArea];
        }
        $type = request('type', 1);
        //type  1:全部  2.代付款 3.待配送 4.配送中 5.已完成
        switch ($type) {
            case 1 :
                break;
            case 2 :
                $where['status'] = 10;
                $where['type'] = 0;
                break;
            case 3 :
                $where['status'] = 20;
                $where['dispatch'] = ['<=', 0];
                $orWhere = $where;
                $orWhere['status'] = 10;
                $orWhere['type'] = 1;
                $where['or'] = ['or', $orWhere];
                break;
            case 4 :
                $worker = new Worker();
                $where['dispatch'] = 1;
                break;
            case 5 :
                $where['status'] = 20;
                $where['dispatch'] = 2;
                break;
            default:
                $this->error = '非法操作';
                return false;
        }
//        dd($where);
        $fields = 'id,shop_id,order_sn,order_amount,bucket_num,status,type,worker_id,dispatch,created_at';
        $rows = $this->_getJoinPageList('orderGoods', $where, $fields, ['id' => 'desc'], 10, 5, 'id,order_id,goods_id,goods_name,goods_price,goods_num', ['shop_id' => $where['shop_id']]);
        $picture = new Picture();
        $shop = new Shop();
        $shopInfo = $shop->_redisGetOneBySid($where['shop_id']);
        if ($rows['data']) {
            if ($rows['next_page_url']) {
                $rows['next_page_url'] = $rows['next_page_url'] . '&type=' . $type . '&mid=' . $GLOBALS['mid'] . '&sid=' . $GLOBALS['shop_id'] . '&aid=' . $GLOBALS['admin_id'];
            }
            foreach ($rows['data'] as &$v) {
                if ($v['order_goods']) {
                    foreach ($v['order_goods'] as &$m) {
                        $m['goods_img'] = url('/') . $picture->config['savePath'] . $GLOBALS['admin_id'] . '/' . $m['goods_id'] . '_1.' . $picture->config['saveExt'];
                    }
                }
                $v['show_cd'] = $shopInfo['cui_dan'];//催单显示控制0 ，1
                $v['show_pay'] = $shopInfo['online_pay'];//催单显示控制0 ，1
                if ($type == 3) {
                    $v['contact'] = $shopInfo['cd_contact'];
                }
                if ($type == 4) {
                    $workerInfo = $worker->_redisGetOneByWid($v['worker_id']);
                    $v['contact'] = $workerInfo['mobile'];
                }
            }
        }
        $txtStr['status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['type'] = [0 => '在线支付', 1 => '线下支付'];
        $txtStr['dispatch'] = [1 => '正在派送', 2 => '已完成', 0 => '未派送', -1 => '过期超时'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getWorkerOrderList()
    {
        $keyword = request('keyword');
        $start = request('time-start');
        $end = request('time-end');
        $where['shop_id'] = $GLOBALS['shop_id'];
        if (!(request('wid') && request('sid'))) {
            $this->error = '非法操作';
            return false;
        }
        $keyword && $where['order_sn'] = $keyword;
        if ($start && !$end) {
            $timeArea = [strtotime($start), strtotime($start) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($end && !$start) {
            $timeArea = [strtotime($end), strtotime($end) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $timeArea[1] += 86399;
            $where['addtime'] = ['between', $timeArea];
        }
        $where['dispatch'] = request('type', 1) - 1;
        if (!$where['dispatch']) {
            $where['dispatch'] = ['<=', 0];
            $where['type'] = 0;
            $where['status'] = 20;
            $orWhere = $where;
            $orWhere['status'] = 10;
            $orWhere['type'] = 1;
            $where['or'] = ['or', $orWhere];
        } else {
            $where['worker_id'] = request('wid');
        }
        $order = ['dispatch' => 'asc', 'id' => 'desc'];
        if (request('type', 1) == 3) {
            $order = ['updated_at' => 'desc'];
        }
        $fields = 'id,shop_id,order_sn,order_amount,bucket_num,status,type,dispatch,mobile,buyer_address,buyer_id,buyer_name,description,created_at';
        $rows = $this->_getJoinPageList('orderGoods', $where, $fields, $order, 10, 5, 'id,order_id,goods_id,goods_name,goods_price,goods_num', ['shop_id' => $where['shop_id']]);
        $picture = new Picture();
        if ($rows['data']) {
            if ($rows['next_page_url']) {
                $rows['next_page_url'] = $rows['next_page_url'] . '&type=' . request('type', 1) . '&wid=' . request('wid') . '&sid=' . request('sid') . '&aid=' . request('aid');
            }
            foreach ($rows['data'] as &$v) {
                if ($v['order_goods']) {
                    foreach ($v['order_goods'] as &$m) {
                        $m['goods_img'] = url('/') . $picture->config['savePath'] . request('aid') . '/' . $m['goods_id'] . '_1.' . $picture->config['saveExt'];
                    }
                }
            }
        }
        $txtStr['status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['type'] = [0 => '在线支付', 1 => '线下支付'];
        $txtStr['dispatch'] = [1 => '正在派送', 2 => '已完成', 0 => '未派送', -1 => '过期超时'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getWorkerSendOrderList()
    {
        $keyword = request('keyword');
        $start = request('time-start');
        $end = request('time-end');
        $where['shop_id'] = request('sid');
        if (!(request('wid') && request('sid'))) {
            $this->error = '非法操作';
            return false;
        }
        $keyword && $where['order_sn'] = $keyword;
        if ($start && !$end) {
            $timeArea = [strtotime($start), strtotime($start) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($end && !$start) {
            $timeArea = [strtotime($end), strtotime($end) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $timeArea[1] += 86399;
            $where['addtime'] = ['between', $timeArea];
        }
        $type = request('type', 1);
        //type  1.配送中 2.已完成
        $where['worker_id'] = request('wid');
        $where['dispatch'] = 1;
        $billOrderWhere = ['pay_status' => 10, 'type' => 1];
        $billModel = 'billOrder';
        $name = 'bill_order';
        if ($type == 2) {
            $where['dispatch'] = 2;
            $billOrderWhere = ['pay_status' => 20, 'type' => 1];
            $billModel = 'payBillOrder';
            $name = 'pay_bill_order';
        }
        $orderFields = 'id,shop_id,bill_id,order_amount,status,type,dispatch,mobile,buyer_id,buyer_address,buyer_name,description,created_at';
        $orderGoodsFields = 'id,order_id,goods_id,goods_name,goods_price,goods_num';
        $billOrderFields = 'id,mid,order_id,sum(order_amount) as money';
        $memberFields = 'id,total_waterbill_num,borrow_bucket_num';
        $rows = $this->multiSelect($orderFields)->withCertain('orderGoods', $orderGoodsFields)
            ->withCertain($billModel, $billOrderFields, $billOrderWhere)
            ->withCertain('member', $memberFields)->multiWhere($where)->multiOrder(['id' => 'asc'])->paginate(5);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 5);
        }
        $picture = new Picture();
        if ($rows['data']) {
            if ($rows['next_page_url']) {
                $rows['next_page_url'] = $rows['next_page_url'] . '&type=' . $type . '&wid=' . request('wid') . '&sid=' . request('sid') . '&aid=' . request('aid');
            }
            foreach ($rows['data'] as &$v) {
                if ($v[$name]) {
                    $v[$name]['money'] = number_format($v[$name]['money'], 2);
                }
                if ($v['order_goods']) {
                    foreach ($v['order_goods'] as &$m) {
                        $m['goods_img'] = url('/') . $picture->config['savePath'] . request('aid') . '/' . $m['goods_id'] . '_1.' . $picture->config['saveExt'];
                    }
                }
            }
        }
        $txtStr['status'] = [10 => '未付款', 20 => '已付款', 0 => '已取消'];
        $txtStr['type'] = [0 => '在线支付', 1 => '线下支付'];
        $txtStr['dispatch'] = [1 => '正在派送', 2 => '已完成', 0 => '未派送', -1 => '过期超时'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getInfoById($orderId)
    {
        $where['shop_id'] = request('sid');
        if (!(request('wid') && request('sid'))) {
            $this->error = '非法操作';
            return false;
        }
        $where['id'] = $orderId;
        $type = request('type');
        //type  1.配送中 2.已完成
        $where['worker_id'] = request('wid');
        $where['dispatch'] = $type - 1;
        $billOrderWhere = ['pay_status' => 10, 'type' => 1];
        $billModel = 'billOrder';
        if ($type == 3) {
            $where['dispatch'] = $type - 1;
            $billOrderWhere = ['pay_status' => 20, 'type' => 1];
            $billModel = 'payBillOrder';
        }
        $orderFields = 'id,shop_id,bill_id,order_amount,status,type,dispatch,mobile,buyer_id,buyer_address,buyer_name,description,created_at';
        $orderGoodsFields = 'id,order_id,goods_id,goods_name,goods_price,goods_num,goods_category_id,bucket_category_id';
        $billOrderFields = 'mid,order_id,order_amount,description';
        $memberFields = 'id,total_waterbill_num,total_bucket_num,borrow_bucket_num,initial_bucket_num,self_bucket_num,total_back_bucket_num';
        if ($type == 2) {
            $res = $this->multiSelect($orderFields)->withCertain('orderGoods', $orderGoodsFields)
                ->withCertain($billModel, $billOrderFields, $billOrderWhere)
                ->withCertain('member', $memberFields)->multiWhere($where)->first();
        } else {
            $orderFields = 'id,buyer_address,back_bucket_num,created_at';
            $orderGoodsFields = 'id,order_id,goods_id,goods_name,goods_price,goods_num';
            $res = $this->multiSelect($orderFields)->withCertain('orderGoods', $orderGoodsFields)->multiWhere($where)->first();
        }
        if ($res) {
            $res = $res->toArray();
            if (isset($res['member']) && $res['member']) {
                $initBucketNum = $res['member']['initial_bucket_num'] + $res['member']['self_bucket_num'];
                $total_bucket_num = $initBucketNum + $res['member']['total_bucket_num'] - $res['member']['total_back_bucket_num'];
                $res['member']['total_bucket_num'] = $total_bucket_num;
            }
            if (isset($res['bill_order']) && $res['bill_order'] && count($res['bill_order']) > 0) {
                $arr = ['money' => 0, 'description' => []];
                foreach ($res['bill_order'] as $k => $v) {
                    $arr['money'] += $v['order_amount'];
                    if ($v['description']) {
                        $arr['description'][] = $v['description'];
                    }
                }
                $res['bill_order'] = $arr;
            }
            if ($type == 3) {
                $bonusLog = new BonusLog();
                $res['bonus_info'] = $bonusLog->_getOne(['order_id' => $orderId], 'recive_order_money,recive_bill_money,bonus');
            }
            $picture = new Picture();
            $res['back'] = 0;
            if ($res['order_goods']) {
                foreach ($res['order_goods'] as &$v) {
                    if ($type == 2 && $v['goods_category_id'] == $this->back_category_id) {
                        $res['back'] = 1;
                    }
                    $v['goods_img'] = url('/') . $picture->config['savePath'] . request('aid') . '/' . $v['goods_id'] . '_1.' . $picture->config['saveExt'];
                }
            }
        }
        return $res;
    }

    public function getOrderInfoById($orderId)
    {
        $where['id'] = $orderId;

        $orderFields = 'id,shop_id,bill_id,order_amount,status,type,dispatch,mobile,buyer_id,buyer_address,buyer_name,description,created_at,admin_id,order_sn';
        $orderGoodsFields = 'id,order_id,goods_id,goods_name,goods_price,goods_num,goods_category_id';
        $billOrderFields = 'mid,order_id,order_amount,description';
        $memberFields = 'id,total_waterbill_num,total_bucket_num,borrow_bucket_num,initial_bucket_num,self_bucket_num,total_back_bucket_num';
        $billOrderWhere = ['pay_status' => 10, 'type' => 1];
        $res = $this->multiSelect($orderFields)->withCertain('orderGoods', $orderGoodsFields)
            ->withCertain('billOrder', $billOrderFields, $billOrderWhere)
            ->withCertain('member', $memberFields)->multiWhere($where)->first();

        if ($res) {
            $res = $res->toArray();
            if (isset($res['member']) && $res['member']) {
                $initBucketNum = $res['member']['initial_bucket_num'] + $res['member']['self_bucket_num'];
                $total_bucket_num = $initBucketNum + $res['member']['total_bucket_num'] - $res['member']['total_back_bucket_num'];
                $res['member']['total_bucket_num'] = $total_bucket_num;
            }
            if (isset($res['bill_order']) && $res['bill_order'] && count($res['bill_order']) > 0) {
                $arr = ['money' => 0, 'description' => []];
                foreach ($res['bill_order'] as $k => $v) {
                    $arr['money'] += $v['order_amount'];
                    if ($v['description']) {
                        $arr['description'][] = $v['description'];
                    }
                }
                $res['bill_order'] = $arr;
            }
            $bonusLog = new BonusLog();
            $bonus = $bonusLog->_getOne(['order_id' => $orderId], 'recive_order_money,recive_bill_money,bonus');
            $res['bonus_info'] = $bonus ? $bonus : [];
            $res['back'] = 0;
        }
        return $res;
    }


    public function getOrderListWithGoods()
    {
        $keyword = request('keyword');
        $where['admin_id'] = request('aid');
        $where['shop_id'] = request('sid');
        $where['buyer_id'] = request('mid');
        if ($keyword) {
            $where['order_sn'] = ['like', '%' . $keyword . '%'];
        }
        return $this->_getJoinPageList('orderGoods', $where, '*', ['sort' => 'asc'], 10, 5, 'id,goods_id,goods_name,goods_price,goods_num', ['shop_id' => $where['shop_id']]);
    }

    public function getOrderListByShopId($shopId)
    {
        $keyword = request('keyword');
        if ($keyword) {
            $where['order_sn'] = ['like', '%' . $keyword . '%'];
        }
        if (request('category_id')) {
            $where['category_id'] = request('category_id');
        }
        $where['shop_id'] = $shopId;
        $where['status'] = ['>', 0];
        $rows = $this->_getPageList($where, 'id,goods_id,goods_name,goods_num,goods_price');
        return $rows;
    }

    public function addOrder()
    {
        $admin_id = $GLOBALS['admin_id'];
        $shop_id = $GLOBALS['shop_id'];
        $mid = $GLOBALS['mid'];
        $key = 'order_' . $admin_id . '_' . $shop_id . '_' . $mid;
        if ($this->redis->exists($key)) {
            $this->error = '您已成功下单，请勿重复下单！';
            return false;
        }
        if (!($mid && $admin_id && $shop_id)) {
            $this->error = '非法操作！';
            return false;
        }
        $goods_ids = request('goods_ids');
        if (!is_array($goods_ids)) {
            $this->error = '非法操作！';
            return false;
        }
        if (count($goods_ids) > 10) {
            $this->error = '每个订单最多10种商品！';
            return false;
        }
        $goods_nums = request('goods_nums');
        if (!is_array($goods_nums)) {
            $this->error = '非法操作！';
            return false;
        }
        $goods = new ShopGoods();
        $where['id'] = ['in', $goods_ids];
        $goodsList = $goods->_getList($where)->toArray();
        if (!$goodsList) {
            $this->error = '获取商品信息失败！';
            return false;
        }
        $totalMoney = 0;
        foreach ($goodsList as $k => $v) {
            $totalMoney += $v['goods_price'] * $goods_nums[$k];
        }
        $create_order_by_self = request('create_order_by_self', 0);
        if ($create_order_by_self) {
            $totalMoney = request('money');
        } else {
//            if ($totalMoney != request('order_amount')) {
//                $this->error = '订单金额与实际金额不符，请重新下单！';
//                return false;
//            }
        }
        $data['bill_id'] = intval(request('bill_id', 0));
        if ($data['bill_id']) {
            $data['status'] = 20;
            $data['payment_time'] = time();
        }
        $data['order_amount'] = $totalMoney;
        $data['order_sn'] = makeOrderSn($mid);
        $data['admin_id'] = intval($admin_id);
        $data['shop_id'] = intval($shop_id);
        $data['buyer_id'] = intval($mid);
        $data['buyer_name'] = request('buyer_name');
        $data['mobile'] = request('mobile');
        $data['type'] = request('type');
        $data['buyer_address'] = request('buyer_address');
        $data['bucket_num'] = array_sum($goods_nums);
        $data['addtime'] = time();
        $data['description'] = trim(request('description'));
        $data['buyer_openid'] = request('buyer_openid', '');

        // 查询购买数量限制
        $memberInfo = (new Member())->_getOneById($mid);
        $shop = new Shop();
        $shopInfo = $shop->_redisGetOneBySid($shop_id);
        if ($shopInfo['send_mode'] == 2 && $memberInfo['worker_id']) {
            $data['worker_id'] = $memberInfo['worker_id'];
            $data['dispatch'] = 1;
        }
        $buy_min = $memberInfo['buy_min'] ? $memberInfo['buy_min'] : $shopInfo['buy_min'];
        $buy_max = $memberInfo['buy_max'] ? $memberInfo['buy_max'] : $shopInfo['buy_max'];
        if ($buy_min) {
            if ($data['bucket_num'] < $buy_min) {
                $this->error = '最小购买数量为' . $buy_min;
                return false;
            }
        }
        if ($buy_max) {
            if ($data['bucket_num'] > $buy_max) {
                $this->error = '最大购买数量为' . $buy_max;
                return false;
            }
        }
        if (!$this->_validate($data)) {
            return false;
        }
        //开启事务
        $this->_start();
        try {
            $orderId = $this->_save($data);
//            if (!$orderId) {
//                $this->error = '保存订单信息失败！';
//                $this->_rollBack(); //回滚
//                return false;
//            }
            $data['id'] = $orderId;
            $orderGoodsData = [];
            foreach ($goodsList as $k => $v) {
                $orderGoodsData[$k] = [
                    'admin_id' => $data['admin_id'],
                    'order_id' => $orderId,
                    'shop_id' => $data['shop_id'],
                    'bill_id' => $data['bill_id'],
                    'shop_goods_id' => $v['id'],
                    'goods_id' => $v['goods_id'],
                    'goods_name' => $v['goods_name'],
                    'goods_price' => $v['goods_price'],
                    'goods_num' => $goods_nums[$k],
                    'goods_category_id' => $v['category_id'],
                    'bucket_category_id' => $v['bucket_category_id'],
                    'brand_id' => $v['brand_id'],
                    'addtime' => $data['addtime'],
                ];
            }
            $data['goods_name'] = $orderGoodsData[0]['goods_name'];
            if (count($orderGoodsData) > 1) {
                $data['goods_name'] .= '...';
            }
            $orderGoods = new OrderGoods();
            $res = $orderGoods->_add($orderGoodsData);
//            if (!$res) {
//                $this->error = '保存订单商品信息失败！';
//                $this->_rollBack(); //回滚
//                return false;
//            }
            //提交事务
            $this->_commit();
            //储存表单提交状态
            $this->redis->setex($key, 5, 1);
            return $data;
        } catch (\Exception $e) {
            $this->_rollBack(); //回滚
            $this->error = '生成订单失败，请稍后再试！';
            return false;
        }

    }

    public function creatOrder($mid, $shop_id, $admin_id, $goods_id, $goods_num, $money)
    {
        if (intval($goods_num) < 1) {
            $this->error = '商品数量必须是数字且不能小于1！';
            return false;
        }
        if ($money < 1) {
            $this->error = '订单金额必须是数字且不能小于1！';
            return false;
        }
        $type = 1; //0.水票 1.零售
        $memberWaterBill = new MemberWaterBill();
        $GoodsData = $memberWaterBill->_getOne(['shop_goods_id' => $goods_id, 'mid' => $mid]);
//        tolog('GoodsData');
//        tolog($GoodsData);
        if ($GoodsData && $GoodsData['rest_num'] >= $goods_num) {
            $type = 0;
            $data['status'] = 20;
            $data['payment_time'] = time();
        }
        if (!($mid && $admin_id && $shop_id && $goods_id)) {
            $this->error = '非法操作！';
            return false;
        }
        if ($type) {
            $goods = new ShopGoods();
            $where['id'] = $goods_id;
            $where['shop_id'] = $shop_id;
            $GoodsData = $goods->_getOne($where)->toArray();
            if (!$GoodsData) {
                $this->error = '获取商品信息失败！';
                return false;
            }
        }
        $shop = new Shop();
        $shopInfo = $shop->_redisGetOneBySid($shop_id);
        if ($shopInfo['send_mode'] == 2) {
            $worker_id = request('worker_id', 0);
            if ($worker_id) {
                $data['worker_id'] = $worker_id;
                $data['dispatch'] = 1;
            }
        }
        $data['bill_id'] = $type ? 0 : $GoodsData['id'];
        $data['order_amount'] = $money;
        $data['order_sn'] = makeOrderSn($mid);
        $data['admin_id'] = intval($admin_id);
        $data['shop_id'] = intval($shop_id);
        $data['buyer_id'] = intval($mid);
        $data['buyer_name'] = request('buyer_name');
        $data['mobile'] = request('mobile');
        $data['type'] = $type;
        $data['buyer_address'] = request('buyer_address');
        $data['bucket_num'] = $goods_num;
        $data['addtime'] = time();
        $data['description'] = trim(request('description'));
        $data['buyer_openid'] = request('buyer_openid', '');
        if (!is_mobile($data['mobile']) && strlen($data['mobile']) == 11) {
            unset($this->rules['mobile']);
        }
        if (!$this->_validate($data)) {
            return false;
        }
        //开启事务
        $this->_start();
//        tolog('data');
//        tolog($data);
        $orderId = $this->_save($data);
//        tolog('orderId:'.$orderId);
        if (!$orderId) {
            $this->error = '保存订单信息失败！';
            $this->_rollBack(); //回滚
            return false;
        }
        $data['id'] = $orderId;
        $data['goods_name'] = $GoodsData['goods_name'];
        $orderGoodsData = [
            'admin_id' => $GoodsData['admin_id'],
            'order_id' => $orderId,
            'shop_id' => $GoodsData['shop_id'],
            'bill_id' => $data['bill_id'],
            'shop_goods_id' => $type ? $GoodsData['id'] : $GoodsData['shop_goods_id'],
            'goods_id' => $GoodsData['goods_id'],
            'goods_name' => $GoodsData['goods_name'],
            'goods_price' => $GoodsData['goods_price'],
            'goods_num' => $goods_num,
            'goods_category_id' => $GoodsData['category_id'],
            'bucket_category_id' => $GoodsData['bucket_category_id'],
            'brand_id' => $GoodsData['brand_id'],
            'addtime' => $data['addtime'],
        ];

//        tolog('orderGoodsData');
//        tolog($orderGoodsData);
        $orderGoods = new OrderGoods();
        $res = $orderGoods->_add($orderGoodsData);
//        tolog('orderGoods:'.$res);
        if (!$res) {
            $this->error = '保存订单商品信息失败！';
            $this->_rollBack(); //回滚
            return false;
        }
        if (!$type) {
            //更新用户余票数量
            $member = new Member();
            $res = $member->_dec(['id' => $mid], 'total_waterbill_num', $goods_num);
//            tolog('member:'.$res);
            if (!$res) {
                $this->error = '更新客户水票信息失败！';
                $this->_rollBack(); //回滚
                return false;
            }
            //更新水票余票数量
            $memberWaterBill = new MemberWaterBill();
            $res = $memberWaterBill->_dec(['id' => $GoodsData['id']], 'rest_num', $goods_num);
//            tolog('memberWaterBill:'.$res);
            if (!$res) {
                $this->error = '更新客户水票信息失败！';
                $this->_rollBack(); //回滚
                return false;
            }
            $memberWaterBill->_redisGenerateBillListByMid($GoodsData['mid']);
            //记录水票消费日志
            $billLog = new MemberWaterBillLog();
            $data['total_num'] = $goods_num;
            $data['goods_id'] = $GoodsData['goods_id'];
            $data['goods_name'] = $GoodsData['goods_name'];
            $data['goods_num'] = $goods_num;
//            tolog('billLog');
//            tolog($billLog);
            $e = $billLog->log($data, $data, 3);
//            tolog('e:'.$e);
            if (!$e) {
                $this->error = '记录水票消费日志失败！';
                $this->_rollBack(); //回滚
                return false;
            }
        }
        //提交事务
        $this->_commit();
        return $data;
    }

    public function addBillOrder()
    {
        $admin_id = $GLOBALS['admin_id'];
        $shop_id = $GLOBALS['shop_id'];
        $mid = $GLOBALS['mid'];
        $key = 'order_' . $admin_id . '_' . $shop_id . '_' . $mid;
        if ($this->redis->exists($key)) {
            $this->error = '您已成功下单，请勿重复下单！';
            return false;
        }
        $id = request('id');
        $num = intval(request('num'));
//        $id = 1;
//        $num = 1;
        if (!($id && $num)) {
            $this->error = '非法操作！';
            return false;
        }

        $memberWaterBill = new MemberWaterBill();
        $info = $memberWaterBill->_getOneById($id);
        if (!$info) {
            $this->error = '获取水票信息失败！';
            return false;
        }
        if ($info['rest_num'] < $num) {
            $this->error = '水票余额不足！';
            return false;
        }
        $order_amount = $info['goods_price'] * $num;
        $data['payment_time'] = time();
        $data['order_sn'] = makeOrderSn($mid);
        $data['admin_id'] = $admin_id;
        $data['shop_id'] = $shop_id;
        $data['buyer_id'] = $mid;
        $data['buyer_name'] = request('buyer_name');
        $data['mobile'] = request('mobile');
        $data['buyer_address'] = request('buyer_address');
        $data['description'] = trim(request('description'));
        $data['order_amount'] = $order_amount;
        $data['bucket_num'] = $num;
        $data['bill_id'] = $info['id'];
        $data['status'] = 20;
        $data['type'] = 0;
        $data['addtime'] = time();
        $data['buyer_openid'] = request('buyer_openid');

        // 查询购买数量限制
        $memberInfo = (new Member())->_getOneById($mid);
        $shop = new Shop();
        $shopInfo = $shop->_redisGetOneBySid($shop_id);
        if ($shopInfo['send_mode'] == 2 && $memberInfo['worker_id']) {
            $data['worker_id'] = $memberInfo['worker_id'];
            $data['dispatch'] = 1;
        }
        /*$buy_min = $memberInfo['buy_min'] ? $memberInfo['buy_min'] : $shopInfo['buy_min'];
        $buy_max = $memberInfo['buy_max'] ? $memberInfo['buy_max'] : $shopInfo['buy_max'];
        if($buy_min) {
            if($data['bucket_num'] < $buy_min){
                $this->error = '最小购买数量为'.$buy_min;
                return false;
            }
        }
        if($buy_max) {
            if($data['bucket_num'] > $buy_max){
                $this->error = '最大购买数量为'.$buy_max;
                return false;
            }
        }*/

        if (!$this->_validate($data)) {
            return false;
        }
        //开启事务
        $this->_start();
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存订单信息失败！';
            $this->_rollBack(); //回滚
            return false;
        }
        $data['id'] = $res;
        $orderGoodsData = [
            'admin_id' => $info['admin_id'],
            'order_id' => $res,
            'shop_id' => $info['shop_id'],
            'bill_id' => $id,
            'shop_goods_id' => $info['shop_goods_id'],
            'goods_id' => $info['goods_id'],
            'goods_name' => $info['goods_name'],
            'goods_price' => $info['goods_price'],
            'goods_num' => $num,
            'goods_category_id' => $info['category_id'],
            'bucket_category_id' => $info['bucket_category_id'],
            'brand_id' => $info['brand_id'],
            'addtime' => $data['addtime'],
        ];
        $orderGoods = new OrderGoods();
        $res = $orderGoods->_add($orderGoodsData);
        if (!$res) {
            $this->error = '保存订单商品信息失败！';
            $this->_rollBack(); //回滚
            return false;
        }
        //更新用户余票数量
        $member = new Member();
        $res = $member->_dec(['id' => $info['mid']], 'total_waterbill_num', $num);
        if (!$res) {
            $this->error = '更新客户水票信息失败！';
            return false;
        }
        //更新水票余票数量
        $memberWaterBill = new MemberWaterBill();
        $res = $memberWaterBill->_dec(['id' => $id], 'rest_num', $num);
        if (!$res) {
            $this->error = '更新客户水票信息失败！';
            return false;
        }
        $memberWaterBill->_redisGenerateBillListByMid($info['mid']);
        //记录水票消费日志
        $billLog = new MemberWaterBillLog();
        $data['total_num'] = $num;
        $data['goods_id'] = $info['goods_id'];
        $data['goods_name'] = $info['goods_name'];
        $data['goods_num'] = $num;
        $e = $billLog->log($data, $data, 3);
        //提交事务
        $this->_commit();
        //储存表单提交状态
        $this->redis->setex($key, 5, 1);
        return $data;
    }

    public function cancel()
    {
        $data['id'] = request('id');
//        $data['reason'] = request('reason');
        $data['status'] = 0;
        $data['dispatch'] = 0;
        if (!$data['id']) {
            $this->error = '请选择要操作的数据！';
            return false;
        }
//        if (!$data['reason']) {
//            $this->error = '请填写取消原因！';
//            return false;
//        }
        $order = $this->_getJionOne('orderGoods', ['id' => $data['id']]);
        if (!$order) {
            $this->error = '该订单不存在！';
            return false;
        }
        if ($order['dispatch'] > 1) {
            $this->error = '非法操作！';
            return false;
        }
        $order = $order->toArray();
        $this->_start();
        try {
            if ($order['bill_id']) {
                $num = $order['order_goods'][0]['goods_num'];
                //退还用户余票
                $member = new Member();
                $member->_inc(['id' => $order['buyer_id']], 'total_waterbill_num', $num);
                //退还水票余票
                $memberWaterBill = new MemberWaterBill();
                $memberWaterBill->_inc(['id' => $order['bill_id']], 'rest_num', $num);
                //  记录水票消费日志
                $order['admin_id'] = plat_admin_id();
                $order['mid'] = $order['buyer_id'];
                $order['waterbill_id'] = $order['bill_id'];
                $order['goods_id'] = $order['order_goods'][0]['goods_id'];
                $order['goods_name'] = $order['order_goods'][0]['goods_name'];
                $order['goods_num'] = $order['order_goods'][0]['goods_num'];
                $billLog = new MemberWaterBillLog();
                $billLog->log($order, $order, 6);
            }
            $this->_save($data);
            $this->_commit();
            return '取消成功';
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '取消失败！';
            return false;
        }
    }

    public function send()
    {
        $data['id'] = request('id');
        $data['worker_id'] = intval(request('worker_id'));
        $data['dispatch'] = 1;
        if (!$data['id']) {
            $this->error = '请选择要操作的数据！';
            return false;
        }
        if (!$data['worker_id']) {
            $this->error = '请选择派送人员！';
            return false;
        }
        $order = $this->_getOneById($data['id']);
        if (!request('type')) {
            if ($order['worker_id']) {
                $this->error = '该订单已派单！';
                return false;
            }
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '派单失败！';
            return false;
        }
        $order = $order->toArray();
        $order['worker_id'] = $data['worker_id'];
        $worker = new Worker();
        $worker->_redisChangeMaxOrderNum($data['worker_id']);
        $orderGoods = new OrderGoods();
        $orderGoodsData = $orderGoods->_getList(['order_id'=>$order['id']],'goods_name')->toArray();
        $order['goods_name'] = $orderGoodsData[0]['goods_name'];
        if (count($orderGoodsData) > 1) {
            $order['goods_name'] .= '...';
        }
        return $order;
    }

    public function workerSend()
    {
        $data['id'] = intval(request('id'));
        $data['worker_id'] = intval(request('worker_id'));
        $data['dispatch'] = 1;
        if (!$data['id']) {
            $this->error = '请选择要接的订单！';
            return false;
        }
        if (!$data['worker_id']) {
            $this->error = '非法操作！';
            return false;
        }
        $order = $this->_getOneById($data['id'], 'id,buyer_id,buyer_openid,worker_id,admin_id,updated_at');
        if ($order['worker_id']) {
            $this->error = '该订单已被抢！';
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '接单失败！';
            return false;
        }
        $order = $order->toArray();
        $order['worker_id'] = $data['worker_id'];
        $worker = new Worker();
        $worker->_redisChangeMaxOrderNum($data['worker_id']);
        $wxTpl = new WxTpl();
        $wxTpl->preSendOrderMsg($order);
        return '接单成功';
    }

    public function workerReSend()
    {
        $data['id'] = intval(request('id'));
        $data['worker_id'] = intval(request('worker_id'));
        $data['dispatch'] = 1;
        if (!$data['id']) {
            $this->error = '请选择要改派的订单！';
            return false;
        }
        if (!$data['worker_id']) {
            $this->error = '非法操作！';
            return false;
        }
        $order = $this->_getOneById($data['id'], 'id,buyer_id,buyer_openid,worker_id,admin_id,updated_at');
        if (!$order) {
            $this->error = '该订单不存在！';
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '改派失败！';
            return false;
        }
        $worker = new Worker();
        $worker->_redisChangeMaxOrderNum($data['worker_id']);
        $worker->_redisChangeMaxOrderNum($order['worker_id'], -1);
        $order = $order->toArray();
        $order['worker_id'] = $data['worker_id'];
        $wxTpl = new WxTpl();
        $wxTpl->preSendOrderMsg($order);
        return '改派成功';
    }

    public function deleteOrder()
    {
        $id = request('id');
        $sql = "delete a,b from `qds_order` as a join  `qds_order_goods` as b on a.id = b.order_id where a.id  = $id";
        $res = DB::delete($sql);
        if (!$res) {
            $this->error = '取消失败，请稍后再试！';
            return false;
        }
        return '取消成功';
    }

    public function delete()
    {
        $id = request('id');
        $buyerId = $GLOBALS['mid'];
        if (!($id && $buyerId)) {
            $this->error = '非法操作！';
            return false;
        }
        $sql = "delete a,b from `qds_order` as a join  `qds_order_goods` as b on a.id = b.order_id where a.id  = $id";
        $res = DB::delete($sql);
        if (!$res) {
            $this->error = '取消失败，请稍后再试！';
            return false;
        }
        return '取消成功';
    }

    public function complete()
    {
        $where['id'] = request('id');
        $where['worker_id'] = intval(request('worker_id'));
        $where['dispatch'] = 1;
        if (!($where['id'] && $where['worker_id'])) {
            $this->error = '非法操作！';
            return false;
        }
        $orderInfo = $this->_getJionOne('orderGoods', $where);
        if (!$orderInfo) {
            $this->error = '该订单不存在！';
            return false;
        }
        $orderInfo = $orderInfo->toArray();
        if ($orderInfo['dispatch'] != 1) {
            $this->error = '非法操作！';
            return false;
        }
        $formId = request('formId');
        $back = request('back');
        $bucket_nums = request('nums', []);
        $bucket_category_ids = request('bucket_category_ids', []);
//        if (!(is_array($bucket_category_ids) && !empty($bucket_category_ids) && is_array($bucket_nums) && !empty($bucket_nums))) {
//            $this->error = '请选择相应的水桶类型并填写相应的数量！';
//            return false;
//        }
//        if (!$bucket_nums) {
//            $this->error = '请输入正确的回桶数量！';
//            return false;
//        }
        if ($back) {
            $bucket_nums = array_filter($bucket_nums);
            foreach ($bucket_nums as $v) {
                if (!is_numeric($v)) {
                    $this->error = '请输入正确的回桶数量！';
                    return false;
                }
            }
            if (array_sum($bucket_nums) > 0) {
                if (!$bucket_category_ids) {
                    $this->error = '请选择水桶品牌！';
                    return false;
                }
                $bucket_category_ids = array_filter($bucket_category_ids);
                foreach ($bucket_category_ids as $v) {
                    if ($v < 1) {
                        $this->error = '请选择水桶品牌！';
                        return false;
                    }
                }
            }
        }
        $buketLog = new BucketLog();
        $res = $buketLog->addLog($bucket_nums, $bucket_category_ids, $orderInfo, $back);
        if (!$res) {
            $this->error = $buketLog->getError();
            return false;
        }
        $worker = new Worker();
        $worker->_redisChangeMaxOrderNum($orderInfo['worker_id'], -1);
        $wxTpl = new WxTpl();
        $orderInfo['back_bucket_num'] = array_sum($bucket_nums);
        $wxTpl->sendCompleteOrderMsg($orderInfo);
        return '操作成功';
    }

    public function complete1()
    {
//        worker/complete （post） 老客户导入接口  参数：id(订单ID)  worker_id  bucket_category_ids(水桶品牌ID-数组) nums(水桶数量-数组)

        $where['id'] = 170;
        $where['worker_id'] = 1;
        $where['dispatch'] = 1;
        if (!($where['id'] && $where['worker_id'])) {
            $this->error = '非法操作！';
            return false;
        }
        $orderInfo = $this->_getJionOne('orderGoods', $where);
        if (!$orderInfo) {
            $this->error = '该订单不存在！';
            return false;
        }
        $orderInfo = $orderInfo->toArray();
        if ($orderInfo['dispatch'] != 1) {
            $this->error = '非法操作！';
            return false;
        }
        $bucket_category_ids = [1, 2];
        $bucket_nums = [1, 1];
        if (!(is_array($bucket_category_ids) && !empty($bucket_category_ids) && is_array($bucket_nums) && !empty($bucket_nums))) {
            $this->error = '请选择相应的水桶类型并填写相应的数量！';
            return false;
        }
        $buketLog = new BucketLog();
        $res = $buketLog->addLog($bucket_nums, $bucket_category_ids, $orderInfo);
        if (!$res) {
            $this->error = $buketLog->getError();
            return false;
        }
        return '操作成功';
    }

    public function dealOrder($order_sn)
    {
        if (!$order_sn) {
            $this->error = '非法操作';
            return false;
        }
        //修改数据库订单状态
        $order = $this->_getJionOne('orderGoods', ['order_sn' => $order_sn]);
        if (!$order) {
            $this->error = '该订单不存在';
            return false;
        }
        $order = $order->toArray();
        if ($order['type'] == 0 && $order['status'] == 10) {
            $data['id'] = $order['id'];
            $data['status'] = 20;
            $data['payment_time'] = time();
            $shop = new Shop();
            $shopInfo = $shop->_redisGetOneBySid($order['shop_id']);
            if ($shopInfo['send_mode'] == 2) {
                $member = new Member();
                $memberInfo = $member->_getOneById($order['buyer_id'], 'worker_id');
                if ($memberInfo['worker_id']) {
                    $data['worker_id'] = $memberInfo['worker_id'];
                    $data['dispatch'] = 1;
                }
            }
            $this->_start();
            try {
                $a = $this->_save($data);
                if (!$a) {
                    $this->_rollBack();
                    $this->error = '更新订单状态失败！';
                    return false;
                }
                $shop = new Shop();
                $shopGoods = new ShopGoods();
                $wxTpl = new WxTpl();
                //更新店铺营业额，需判断是否是线上订单才可
                if (!$order['type'] && !$order['bill_id']) {
                    $b = $shop->_inc(['id' => $order['shop_id']], 'sale_money', $order['order_amount']);
                    if (!$b) {
                        $this->_rollBack();
                        $this->error = '更新店铺营业额失败！';
                        return false;
                    }
                }
                //更新商品销量
                foreach ($order['order_goods'] as $v) {
                    $c = $shopGoods->_updateOrigin(['id' => $v['shop_goods_id']], ['sale_num' => "`sale_num` + {$v['goods_num']}"]);
                    if (!$c) {
                        $this->_rollBack();
                        $this->error = '更新商品销量失败！';
                        return false;
                    }
                }

                $this->_commit();
                $orderData = $order;
                $orderData['goods_name'] = $order['order_goods'][0]['goods_name'];
                if (count($order['order_goods']) > 1) {
                    $orderData['goods_name'] .= '...';
                }
                $wxTpl->newOrderMsg($orderData, $order['shop_id']);
                $wxTpl->sendReceiveMsg($orderData, 1);
                (new \App\Support\Printer())->typeSetting($orderData);
                return true;
            } catch (\Exception $e) {
                $this->_rollBack();
                if ($this->error == '') {
                    $this->error = '更新订单状态失败！';
                }
                return false;
            }
        }
        return true;
    }


    public function overTime()
    {
        $data['dispatch'] = -1;
        //超过30分钟判定超时
        $time = time() - 1800;
        $where['addtime'] = ['<', $time];
        $where['status'] = 20;
        $where['dispatch'] = 0;
        $where['type'] = 0;
        //线上订单
        $this->_update($where, $data);
        $where['status'] = 10;
        $where['type'] = 1;
        //线下订单
        $this->_update($where, $data);
    }

    public function clear()
    {
        //超过30分钟判定超时
        $time = time() - 1800;
        //线上订单
        $sql = "delete a,b from `qds_order` as a join  `qds_order_goods` as b on a.id = b.order_id where a.addtime  <= $time and a.status=10 and a.type=0";
        DB::delete($sql);
    }

    public function checkShareOrder($where, $address)
    {
        $flag = true;
        $orders = self::_getList($where)->toArray();
        if (count($orders)) {
            foreach ($orders as $items) {
                if (($items['status'] == 20 && $items['dispatch'] < 2) ||
                    ($items['type'] == 1 && $items['dispatch'] < 2)) {
                    // 判断订单地址是否有未送达的订单
                    if ($address == $items['buyer_address']) {
                        $flag = false;
                        break;
                    }
                }
            }
        }

        return $flag;
    }

}
